<template>
  <el-dialog
    :visible.sync="visible"
    width="60%"
    @close="handleClose"
    :title="dialogTitle"
  >
    <div class="dict-detail">
      <div class="form-row">
        <span class="label">字典类型名称：</span>
        <el-input
          v-model="dictTypeType"
          placeholder="请输入字典类型名称"
          style="width: 300px;"
        />
        <div style="margin-left: auto;">
          <el-button type="primary" @click="addItem">新增行</el-button>
          <el-button type="danger" :disabled="!multipleSelection.length" @click="deleteSelected">
            删除选中
          </el-button>
        </div>
        
      </div>

      <!-- 可编辑表格 -->
      <el-table
        :data="detailList"
        border
        stripe
        style="width: 100%; margin-top: 10px;"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column label="字典项名称">
          <template #default="scope">
            <el-input
              v-model="scope.row.name"
              placeholder="请输入名称"
              clearable
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column label="字典项值">
          <template #default="scope">
            <el-input
              v-model="scope.row.value"
              placeholder="请输入值"
              clearable
              size="small"
            />
          </template>
        </el-table-column>
      </el-table>

      <div class="footer-btns">
        <el-button type="primary" @click="confirm">确定</el-button>
        <el-button @click="handleClose">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: 'DictDetailDialog',
  props: {
    visible: Boolean,
    dictType: Object, 
    dictTypeId: Number 
  },
  data() {
    return {
      dictTypeType: '',
      detailList: [],
      multipleSelection: [],
      loading: false,
      debounceTimer: null, // 防抖定时器
      typeExists: false, 
      checkLoading: false 
    }
  },
  computed: {
    dialogTitle() {
      return this.dictType ? '修改字典类型' : '新增字典类型'
    }
  },
  watch: {
    visible(val) {
      // 弹窗打开时加载数据
      if (val && this.dictType) {
        this.dictTypeType = this.dictType.type
        this.loadDictionaryItems(this.dictType.type)
      } else if (val && !this.dictType) {
        // 新增时清空
        this.dictTypeType = ''
        this.detailList = []
      }
    },
    //监听字典类型输入变化
    dictTypeType(newVal) {
      if (newVal.trim()) {
        this.checkTypeExists(newVal.trim());
      } else {
        // 输入清空时重置状态
        this.typeExists = false;
      }
    }
  },
  methods: {
    /** 检查类型是否已存在 */
    async checkTypeExists(type) {
      if (!type) return;
      this.checkLoading = true;

      this.$http.get('/checkDictionaryTypeExists?type=' + type ).then(res => {
        this.typeExists = res.data;
      }).catch(() => {
        this.$message.error('请求错误')
      })
      this.checkLoading = false;
    },

    /** 从后台加载该类型下的字典项 */
    async loadDictionaryItems(type) {
      this.loading = true
      this.$http.get('/getAllDictionaryByType?type=' + type).then(res => {
        if (res.data) {
          this.detailList = res.data
        } else if (res.data.code === 200) {
          this.detailList = res.data.data
        } else {
          this.detailList = []
        }
      }).catch(() => {
        this.$message.error('请求错误')
      })
      this.loading = false
    },

    /** 新增行 */
    addItem() {
      this.detailList.push({
        id: null,
        name: '',
        value: ''
      })
    },

    /** 选中变化 */
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    /** 删除选中行 */
    deleteSelected() {
      this.$confirm('确认删除选中的字典项吗？', '提示', { type: 'warning' }).then(() => {
          const selected = this.multipleSelection
          this.detailList = this.detailList.filter(item => !selected.includes(item))
          this.$message.success('删除成功')
        })
    },

    /** 提交（新增或修改） */
  async confirm() {
      if (!this.dictTypeType.trim()) {
        this.$message.warning('请填写字典类型名称')
        return
      }

      if (!this.dictTypeId && this.typeExists) {
        this.$message.error('类型已存在，无法添加');
        return;
      }

      const payload = {
        id: this.dictTypeId ? this.dictTypeId : 0,
        type: this.dictTypeType,
        detailList: this.detailList.map(item => ({
          id: item.id || null,
          type: this.dictTypeType,
          name: item.name.trim(),
          value: item.value.trim()
        }))
      }

      if (payload.detailList.length > 0 && payload.detailList.some(d => !d.name || !d.value)) {
        this.$message.warning('字典项名称和值不能为空')
        return
      }

      this.$http.post('/saveDictionary', payload).then(res => {
        if (res.data && res.status === 200) {
          this.$message.success('保存成功')
          this.$emit('refresh')
          this.handleClose()
        } else {
          this.$message.error(res.data.msg || '保存失败')
        }
      }).catch(() => {
        this.$message.error('请求出错，请检查后端接口')
      })
    },

    /** 关闭弹窗 */
    handleClose() {
      this.multipleSelection = []
      this.$emit('closeDialog')
    }
  }
}
</script>

<style scoped>
.dict-detail {
  padding: 10px 0;
}
.form-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
.label {
  font-weight: bold;
}
.footer-btns {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 40px;
}
.note {
  margin-top: 10px;
  color: #888;
  text-align: center;
}
</style>
